/*
 * @Author: AuroCaffe 18509564594@163.com
 * @Date: 2025-01-06 18:51:49
 * @LastEditors: AuroCaffe 18509564594@163.com
 * @LastEditTime: 2025-01-06 18:51:49
 * @FilePath: \HuiLin\utils\pageActivityManager.js
 * @Description: 页面活跃状态管理器 - 管理页面的活跃状态和定时器
 */

// 页面活跃状态管理
class PageActivityManager {
    constructor() {
        // 活跃页面映射
        this.activePages = new Map();
        // 页面定时器映射
        this.pageTimers = new Map();
        // 页面统计信息
        this.stats = {
            totalPages: 0,
            activePages: 0,
            totalTimers: 0
        };
    }

    /**
     * 注册页面
     * @param {string} pageId - 页面唯一ID
     * @param {Object} pageInstance - 页面实例
     */
    registerPage(pageId, pageInstance) {
        if (!pageId || !pageInstance) {
            console.warn('[pageActivityManager] 注册页面失败：缺少必要参数');
            return false;
        }

        this.activePages.set(pageId, {
            instance: pageInstance,
            isActive: true,
            registerTime: Date.now(),
            lastActiveTime: Date.now()
        });

        this.updateStats();
        console.log(`[pageActivityManager] 页面已注册: ${pageId}`);
        return true;
    }

    /**
     * 设置页面为非活跃状态
     * @param {string} pageId - 页面唯一ID
     */
    setPageInactive(pageId) {
        const pageInfo = this.activePages.get(pageId);
        if (pageInfo) {
            pageInfo.isActive = false;
            pageInfo.lastActiveTime = Date.now();
            console.log(`[pageActivityManager] 页面设置为非活跃: ${pageId}`);
        }
        this.updateStats();
    }

    /**
     * 注销页面
     * @param {string} pageId - 页面唯一ID
     */
    unregisterPage(pageId) {
        // 清除页面相关的所有定时器
        this.clearPageTimers(pageId);
        
        // 移除页面
        const removed = this.activePages.delete(pageId);
        if (removed) {
            console.log(`[pageActivityManager] 页面已注销: ${pageId}`);
        }
        
        this.updateStats();
        return removed;
    }

    /**
     * 检查页面是否活跃
     * @param {string} pageId - 页面唯一ID
     * @returns {boolean}
     */
    isPageActive(pageId) {
        const pageInfo = this.activePages.get(pageId);
        return pageInfo ? pageInfo.isActive : false;
    }

    /**
     * 获取页面信息
     * @param {string} pageId - 页面唯一ID
     * @returns {Object|null}
     */
    getPageInfo(pageId) {
        return this.activePages.get(pageId) || null;
    }

    /**
     * 创建页面定时器
     * @param {string} pageId - 页面唯一ID
     * @param {string} timerId - 定时器ID
     * @param {Function} callback - 回调函数
     * @param {number} interval - 间隔时间(毫秒)
     * @param {string} description - 定时器描述
     */
    createPageTimer(pageId, timerId, callback, interval = 5000, description = '') {
        if (!pageId || !timerId || !callback) {
            console.warn('[pageActivityManager] 创建定时器失败：缺少必要参数');
            return false;
        }

        // 先清除已存在的定时器
        this.clearPageTimer(pageId, timerId);

        // 创建新的定时器
        const timer = setInterval(() => {
            // 检查页面是否仍然活跃
            if (this.isPageActive(pageId)) {
                try {
                    callback();
                } catch (error) {
                    console.error(`[pageActivityManager] 定时器执行错误: ${timerId}`, error);
                }
            } else {
                // 页面不活跃，清除定时器
                console.log(`[pageActivityManager] 页面不活跃，清除定时器: ${pageId} - ${timerId}`);
                this.clearPageTimer(pageId, timerId);
            }
        }, interval);

        // 存储定时器信息
        if (!this.pageTimers.has(pageId)) {
            this.pageTimers.set(pageId, new Map());
        }
        
        this.pageTimers.get(pageId).set(timerId, {
            timer: timer,
            interval: interval,
            description: description,
            createTime: Date.now(),
            lastExecuteTime: null
        });

        console.log(`[pageActivityManager] 定时器已创建: ${pageId} - ${timerId} (${interval}ms)`);
        this.updateStats();
        return true;
    }

    /**
     * 清除页面定时器
     * @param {string} pageId - 页面唯一ID
     * @param {string} timerId - 定时器ID
     */
    clearPageTimer(pageId, timerId) {
        const pageTimers = this.pageTimers.get(pageId);
        if (pageTimers) {
            const timerInfo = pageTimers.get(timerId);
            if (timerInfo) {
                clearInterval(timerInfo.timer);
                pageTimers.delete(timerId);
                console.log(`[pageActivityManager] 定时器已清除: ${pageId} - ${timerId}`);
                
                // 如果页面没有定时器了，删除页面定时器映射
                if (pageTimers.size === 0) {
                    this.pageTimers.delete(pageId);
                }
            }
        }
        this.updateStats();
    }

    /**
     * 清除页面所有定时器
     * @param {string} pageId - 页面唯一ID
     */
    clearPageTimers(pageId) {
        const pageTimers = this.pageTimers.get(pageId);
        if (pageTimers) {
            pageTimers.forEach((timerInfo, timerId) => {
                clearInterval(timerInfo.timer);
            });
            this.pageTimers.delete(pageId);
            console.log(`[pageActivityManager] 页面所有定时器已清除: ${pageId}`);
        }
        this.updateStats();
    }

    /**
     * 清除所有定时器
     */
    clearAllTimers() {
        this.pageTimers.forEach((pageTimers, pageId) => {
            pageTimers.forEach((timerInfo, timerId) => {
                clearInterval(timerInfo.timer);
            });
        });
        this.pageTimers.clear();
        console.log('[pageActivityManager] 所有定时器已清除');
        this.updateStats();
    }

    /**
     * 获取页面定时器状态
     * @param {string} pageId - 页面唯一ID
     * @returns {Object}
     */
    getPageTimerStatus(pageId) {
        const pageTimers = this.pageTimers.get(pageId);
        if (!pageTimers) {
            return {
                pageId: pageId,
                hasTimers: false,
                timerCount: 0,
                timers: []
            };
        }

        const timers = [];
        pageTimers.forEach((timerInfo, timerId) => {
            timers.push({
                timerId: timerId,
                interval: timerInfo.interval,
                description: timerInfo.description,
                createTime: timerInfo.createTime,
                lastExecuteTime: timerInfo.lastExecuteTime
            });
        });

        return {
            pageId: pageId,
            hasTimers: true,
            timerCount: timers.length,
            timers: timers
        };
    }

    /**
     * 获取活跃页面列表
     * @returns {Array}
     */
    getActivePages() {
        const activePages = [];
        this.activePages.forEach((pageInfo, pageId) => {
            if (pageInfo.isActive) {
                activePages.push({
                    pageId: pageId,
                    registerTime: pageInfo.registerTime,
                    lastActiveTime: pageInfo.lastActiveTime,
                    activeDuration: Date.now() - pageInfo.registerTime
                });
            }
        });
        return activePages;
    }

    /**
     * 获取统计信息
     * @returns {Object}
     */
    getStats() {
        return {
            ...this.stats,
            activePagesList: this.getActivePages()
        };
    }

    /**
     * 更新统计信息
     */
    updateStats() {
        this.stats.totalPages = this.activePages.size;
        this.stats.activePages = this.getActivePages().length;
        
        let totalTimers = 0;
        this.pageTimers.forEach(pageTimers => {
            totalTimers += pageTimers.size;
        });
        this.stats.totalTimers = totalTimers;
    }

    /**
     * 清理过期页面（可选功能）
     * @param {number} maxInactiveTime - 最大非活跃时间(毫秒)
     */
    cleanupInactivePages(maxInactiveTime = 30 * 60 * 1000) { // 默认30分钟
        const now = Date.now();
        const pagesToRemove = [];

        this.activePages.forEach((pageInfo, pageId) => {
            if (!pageInfo.isActive && (now - pageInfo.lastActiveTime) > maxInactiveTime) {
                pagesToRemove.push(pageId);
            }
        });

        pagesToRemove.forEach(pageId => {
            this.unregisterPage(pageId);
        });

        if (pagesToRemove.length > 0) {
            console.log(`[pageActivityManager] 清理了 ${pagesToRemove.length} 个过期页面`);
        }
    }
}

// 创建单例实例
const pageActivityManager = new PageActivityManager();

// 导出单例
export default pageActivityManager; 